const { writeFile, ensureFile, existsSync } = require('fs-extra');
const path = require('path');
const { DomainConfig } = require('./domain.config');
const { execSync } = require('child_process')
const { isCCWEB } = require('./envUtil');

const cache = {};

/**
 * 领域Expose缓存
 * 自动加载 domain/${domainName}/exposes.js,
 */
const getDomainExposesCache = () => {
  Object.entries(DomainConfig).forEach(([domainName]) => {
    const fpath = path.join(process.cwd(), `domain/${domainName}/exposes.js`);
    let exposes = new Set();

    // 加载 exposes.js
    // if (process.env.REEXPOSE !== 'true' && existsSync(fpath) && Array.isArray(require(fpath))) {
    //   exposes = new Set(require(fpath));
    // }
    cache[domainName] = {
      exposes,
      fpath,
    };
  });
  return cache;
};


function exposesComment() {
  return [
    '/**',
    isCCWEB() 
      ? '本文件由 npx cexp 自动生成, 请勿更改' 
      : '本文件由 npx cexp 自动生成, 请复制到 saas-hsy-h5-mainapp/domain/',
    '更新时间: ' + new Date().toLocaleString(),
    '最后更新: ' + execSync('git config --get "user.name"').toString().trim() + `<${execSync('git config --get "user.email"').toString().trim()}>`,
    '仓库地址: ' + execSync('git remote get-url origin').toString().trim(),
    '分支名称: ' + execSync('git rev-parse --abbrev-ref HEAD').toString().trim(),
    '*\/\n'
  ].join('\n * ');
}

/**
 * 保存exposes
 */
const saveDomainExposes = () => {
  const writeAll = Object.entries(cache).map(([_, { exposes, fpath }]) => {
    if (exposes.size > 0) {
      const code =
        'module.exports = [\n' +
        Array.from(exposes)
          .sort()
          .map((it) => `'${it}'`)
          .join(',\n') +
        '\n]\n';

      const dirPath = path.dirname(fpath);
      const jsFilePath = process.env.CURRENT_DOMAIN ? path.join(dirPath, process.env.CURRENT_DOMAIN + '.exposes.js') : path.join(dirPath, 'exposes.js');
      // @ts-ignore
      return ensureFile(jsFilePath).then(() => writeFile(jsFilePath, exposesComment() + code));
    }
    return Promise.resolve('ok');
  });
  // @ts-ignore
  return Promise.all(writeAll);
};

function fileComment() {
  return [
    '/**',
    '本文件由 npx cexp 自动生成,请复制到 saas-cc-web/src/exposes/',
    '更新时间: ' + new Date().toLocaleString(),
    '最后更新: ' + execSync('git config --get "user.name"').toString().trim() + `<${execSync('git config --get "user.email"').toString().trim()}>`,
    '仓库地址: ' + execSync('git remote get-url origin').toString().trim(),
    '分支名称: ' + execSync('git rev-parse --abbrev-ref HEAD').toString().trim(),
    '*\/'
  ].join('\n * ');
}

/**
 * 生成远程依赖导出代码
 */
const saveRemoteExposes = () => {

  const writeAll = Object.entries(cache).map(([_, { exposes, fpath }]) => {
    if (exposes.size > 0) {
      const code =
        '\n' +
        Array.from(exposes)
          .sort()
          .map((it) => `import '${it}';`)
          .join('\n') +
        '\n';

      const tsFilepath = path.join(path.dirname(fpath.replace(/\.js$/, '.ts')), process.env.CURRENT_DOMAIN + '.expose.ts')
      // @ts-ignore
      return ensureFile(tsFilepath).then(() => writeFile(tsFilepath, fileComment() + code));
    }
    return Promise.resolve('ok');
  });
  // @ts-ignore
  return Promise.all(writeAll);
};

module.exports = {
  saveDomainExposes,
  getDomainExposesCache,
  saveRemoteExposes,
};
